package cn.android666.audiorecorder.aac

import cn.android666.audiorecorder.objectpool.ByteBufferPool
import timber.log.Timber
import java.nio.ByteBuffer
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean

/** AAC保存线程 */
class AACSaveThread(private val aacByteBufferPool: ByteBufferPool, sampleRateInHz: Int, channelCount: Int): Thread() {

    private val aacSaver = AACSaver(sampleRateInHz, channelCount)
    private val aacQueue = ArrayBlockingQueue<ByteBuffer>(3)
    private var needRun = AtomicBoolean(true)

    fun addAacBytes(aacByteBuffer: ByteBuffer) {
        val isSuccess = aacQueue.offer(aacByteBuffer)
        if (!isSuccess) {
            Timber.e("保存aac时队列装不下了，丢帧")
        }
    }

    override fun run() {
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO)
        while (needRun.get()) {
            aacQueue.poll(30L, TimeUnit.MILLISECONDS)?.let { aacByteBuffer ->
                aacSaver.write(aacByteBuffer)
                aacByteBufferPool.returnObject(aacByteBuffer)
            }
        }
        aacSaver.close()
    }

    fun close() {
        needRun.set(false)
    }
}